from machine import UART, Pin

import oled
import util

uart = UART(0, baudrate=115200, bits=8, parity=None, stop=1, tx=Pin(0), rx=Pin(1))


async def read_message():
    global uart
    while True:
        print("123")
        if uart.any():
            response = uart.read(1024)
            print(response)


def send_message(input: bytes, response_num: int):
    global uart
    print("正在执行\t", util.response_bytes_to_string(input))
    uart.write(input)
    response_list = []
    while True:
        if uart.any():
            response = uart.read(1024)  # 读取最多 1024 字节的数据
            response_str = util.response_bytes_to_string(response)
            response_list.append(response_str)
            if response_num is None:
                break
        if len(response_list) == response_num:
            break
    print("返回结果\t", response_list)
    return response_list


def init_Server():
    print("开始连接wifi")
    command = [
        'AT+CWMODE=1',
        'AT+CIPMODE=1',
        'AT+CWSAP=demo-DX-wifi,123456789',
        'AT+CIPSERVER=1,9527,TCP,2',
        'AT+CIPSEND'
    ]
    for e in command:
        send_message(util.request_string_to_bytes(e), 1)
    ip = send_message(util.request_string_to_bytes('AT+CIFSR'), 1)
    # 标记结束时间

    return ip


def init_mqtt_client():
    tip_name = 'pico_01'
    # send_message(util.request_string_to_bytes('AT+MQTTCLEAN'), 1)
    send_message(util.request_string_to_bytes('AT+CWMODE=0'), 1)
    # 检查wifi连接状态
    while True:
        response = send_message(util.request_string_to_bytes('AT+CWSTATE?'), 1)
        response_str = response[0]
        parts = response_str.split(':')
        print(parts)
        status_part = parts[1].split(',')[0]
        status_code = status_part.strip()

        if status_code == '0':
            print("未连接")
            send_message(util.request_string_to_bytes('AT+CWJAP=DoDayum-home,970617baiyu'), 1)
        elif status_code == '1':
            print("连接上了，但没有ipv4地址")
        elif status_code == '2':
            print("连接上了，有ipv4地址了")
            break
        elif status_code == '3':
            print("正在连接/重连")
        elif status_code == '4':
            print("断开")
            send_message(util.request_string_to_bytes('AT+CWJAP=DoDayum-home,970617baiyu'), 1)

    send_message(util.request_string_to_bytes('AT+MQTTLONGCLIENTID=mqtt_demo_rpi'), 1)
    send_message(util.request_string_to_bytes('AT+MQTTCONN=192.168.31.134,1883,0'), 2)
    send_message(util.request_string_to_bytes('AT+MQTTUNSUB=' + tip_name), 1)
    send_message(util.request_string_to_bytes('AT+MQTTSUB=' + tip_name + ',0'), 1)


def demo_send_message(input: str):
    global uart
    print("正在执行", input)
    input = util.request_string_to_bytes(input)
    oled.add_write_message(util.response_bytes_to_string(input))
    uart.write(input)
    while True:
        if uart.any():
            response = uart.read(1024)  # 读取最多 1024 字节的数据
            print(response)
            oled.add_write_message(util.response_bytes_to_string(response))


def get_ip():
    global uart
    input = util.request_string_to_bytes('AT+CIPSTA?')
    # oled.add_write_message(util.response_bytes_to_string(input))
    uart.write(input)
    while True:
        if uart.any():
            response = uart.read(1024)  # 读取最多 1024 字节的数据
            break
    a_str = response.decode('utf-8')
    config_dict = {}
    lines = a_str.split('\r\n')
    for line in lines:
        line = line.strip()
        if not line or line == 'OK':
            continue
        key_value = line.split(':')
        key = key_value[1]
        value = key_value[2].strip()
        config_dict[key] = value
    oled.add_write_message(config_dict.get('ip'))
    return config_dict
